<template>
  <div class="bideliRecord">
    <leftListRightDataLayout>
      <div slot="list_left" class="list_left">
        <h3 class="fontsize18">{{$t('myAdd.bideli.saveMoneyLive')}} <span class="back pointer" @click="goBack">< {{$t('myAdd.bideli.prevPage')}}</span></h3>
        <ul>
          <li class="fontsize14 pointer" @click="changeSideBar('myInvestment')" :class="{activeLi: sidebarTab === 'myInvestment'}"><i class="icon-money fontsize16"></i>{{$t('myAdd.bideli.myPosition')}}</li>
          <li class="fontsize14 pointer" @click="changeSideBar('incomeDetail')" :class="{activeLi: sidebarTab === 'incomeDetail'}"><i class="icon-bill fontsize16"></i>{{$t('myAdd.bideli.incomeBreakdown')}}</li>
        </ul>
      </div>
      <div slot="right_data" class="right_data">
        <div class="myInvestment" v-if="sidebarTab === 'myInvestment'">
          <div class="tab clearfix">
            <span class="fontsize16 pointer tabSpan" @click="changeTab('processing')" :class="{tabActive: investmentTab === 'processing'}">{{$t('myAdd.bideli.progressing')}}</span>
            <span class="fontsize16 pointer tabSpan" @click="changeTab('historicalInvestment')" :class="{tabActive: investmentTab === 'historicalInvestment'}">{{$t('myAdd.bideli.historicalPosition')}}</span>
            <div class="selection clearfix">
              <div class="selectSymbol">
                <inline-input
                  v-bind:property = "formList.currencySelection"
                  v-model = "formList.currencySelection.value"
                  v-on:onevents = "somethings">
                </inline-input>
              </div>
              <div class="date" v-show="investmentTab === 'historicalInvestment'">
                <Datepicker
                  :value="dataTimePickerValue"
                  name="uniquename"
                  :inline="false"
                  :minimumView="'month'"
                  :maximumView="'month'"
                  @selected="chooseMonth"
                  :language="dataTimePickerLanguage"
                  format="yyyy-MM"
                  :disabledDates="disabledDates"
                >
                </Datepicker>
                <span class="iconSpan"><i class="icon-calendar"></i></span>
              </div>
            </div>
          </div>
          <div class="table">
            <table class="ingTable" v-show="investmentTab === 'processing'">
              <tbody>
                <tr class="title_tr">
                  <td class="time borderbox">{{$t('myAdd.bideli.purchaseTime')}}</td>
                  <td class="name">{{$t('myAdd.bideli.productName')}}</td>
                  <td class="cycle">{{$t('myAdd.bideli.revenueCycle')}}</td>
                  <td class="amount">{{$t('myAdd.bideli.buyNumber')}}</td>
                  <td class="status">{{$t('myAdd.bideli.status')}}</td>
                  <td class="yesToday_income">{{$t('myAdd.bideli.yesterdayEarnings')}}</td>
                  <td class="operate">{{$t('myAdd.bideli.operating')}}</td>
                </tr>
                <tr class="data_tr" v-for="(item, index) in investmentProcessingData" :key="index" :class="{'subbgColor': !((index + 1) % 2)}">
                  <td class="time borderbox">{{item.time}}</td>
                  <td class="name">{{item.title}}</td>
                  <td class="cycle">{{item.period}}</td>
                  <td class="amount">{{item.quantity}} {{item.symbol}}</td>
                  <td class="status">{{statusText}}</td>
                  <td class="yesToday_income yesToday_income_data">+{{item.yesterDayEarnings}} {{item.symbol}}</td>
                  <td class="operate operate_detail pointer" @click="toBideliBuying(item)">{{$t('myAdd.bideli.buyAgain')}}</td>
                </tr>
              </tbody>
            </table>
            <noData v-if="!investmentProcessingDataLeng && investmentTab === 'processing'"></noData>
            <VPagination
              v-if="(investmentProcessingDataPage.count/investmentProcessingDataPage.pageSize) > 1 && investmentTab === 'processing'"
              :total="investmentProcessingDataPage.count"
              :current-page='investmentProcessingDataPage.page'
              :display='investmentProcessingDataPage.pageSize'
              @pagechange="investmentProcessingDataPageChange($event)" class="page">
            </VPagination>
            <table class="historicalInvestment_table" v-show="investmentTab === 'historicalInvestment'">
              <tbody>
                <tr class="title_tr">
                  <td class="time">{{$t('myAdd.bideli.purchaseTime')}}</td>
                  <td class="name">{{$t('myAdd.bideli.productName')}}</td>
                  <td class="cycle">{{$t('myAdd.bideli.revenueCycle')}}</td>
                  <td class="amount">{{$t('myAdd.bideli.buyNumber')}}</td>
                  <td class="status">{{$t('myAdd.bideli.status')}}</td>
                  <td class="total_income">{{$t('myAdd.bideli.cumulativeIncome')}}</td>
                </tr>
                <tr class="data_tr" v-for="(item, index) in investmentHistoryData" :key="index" :class="{'subbgColor': !((index + 1) % 2)}">
                  <td class="time">{{item.time}}</td>
                  <td class="name">{{item.title}}</td>
                  <td class="cycle">{{item.period}}</td>
                  <td class="amount">{{item.quantity}} {{item.symbol}}</td>
                  <td class="status">{{statusText}}</td>
                  <td class="total_income total_income_data pointer" @click="toBideliBuying(item)">+{{item.yesterDayEarnings}} {{item.symbol}}</td>
                </tr>
              </tbody>
            </table>
            <noData v-if="!investmentHistoryDataLeng && investmentTab === 'historicalInvestment'"></noData>
            <VPagination
              v-if="(investmentHistoryDataPage.count/investmentHistoryDataPage.pageSize) > 1 && investmentTab === 'historicalInvestment'"
              :total="investmentHistoryDataPage.count"
              :current-page='investmentHistoryDataPage.page'
              :display='investmentHistoryDataPage.pageSize'
              @pagechange="investmentHistoryDataPageChange($event)" class="page">
            </VPagination>
          </div>
        </div>
        <div class="incomeBreakdown" v-if="sidebarTab === 'incomeDetail'">
          <div class="tab">
            <span class="fontsize16">收益明细</span>
            <div class="selection clearfix">
              <div class="selectSymbol">
                <inline-input
                  v-bind:property = "formList.incomeCurrencySelection"
                  v-model = "formList.incomeCurrencySelection.value"
                  v-on:onevents = "somethings">
                </inline-input>
              </div>
              <div class="date">
                <Datepicker
                  :value="dataTimePickerValue"
                  name="uniquename"
                  :inline="false"
                  :minimumView="'month'"
                  :maximumView="'month'"
                  @selected="chooseMonth"
                  :language="dataTimePickerLanguage"
                  format="yyyy-MM"
                  :disabledDates="disabledDates"
                >
                </Datepicker>
                <span class="iconSpan"><i class="icon-calendar"></i></span>
              </div>
              <div class="totalEarnings">
                + {{totalEarnings}} {{formList.incomeCurrencySelection.value}}
              </div>
            </div>
          </div>
          <div class="table">
            <table class="incomeBreakdown_table">
              <tbody>
                <tr class="title_tr">
                  <td class="time">{{$t('myAdd.bideli.purchaseTime')}}</td>
                  <td class="name">{{$t('myAdd.bideli.productName')}}</td>
                  <td class="amount">{{$t('myAdd.bideli.buyNumber')}}</td>
                  <td class="income">{{$t('myAdd.bideli.income')}}</td>
                </tr>
                <tr class="data_tr" v-for="(item, index) in incomeRecordData" :key="index" :class="{'subbgColor': !((index + 1) % 2)}">
                  <td class="time">{{item.time}}</td>
                  <td class="name">{{item.name}}</td>
                  <td class="amount">{{item.buyQuantity}} {{item.coin}}</td>
                  <td class="income obvious">+{{item.quantity}} {{item.coin}}</td>
                </tr>
              </tbody>
            </table>
            <noData v-if="!incomeRecordDataLeng"></noData>
            <VPagination
              v-if="(incomeRecordDataPage.count/incomeRecordDataPage.pageSize) > 1"
              :total="incomeRecordDataPage.count"
              :current-page='incomeRecordDataPage.page'
              :display='incomeRecordDataPage.pageSize'
              @pagechange="incomeRecordDataPageChange($event)" class="page">
            </VPagination>
          </div>
        </div>
      </div>
    </leftListRightDataLayout>
    <span v-if="publicInfo && optionListCoin"></span>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import leftListRightDataLayout from '@/components/addPage/common/leftListRightDataLayout'
  import InlineInput from '@/components/common/inlineInput'
  import Datepicker from 'vuejs-datepicker'
  import {en, zh, ko} from 'vuejs-datepicker/dist/locale'
  import VPagination from '@/components/common/pagination'
  import noData from '@/components/addPage/common/noData'
  export default {
    name: 'bideliRecord',
    components: { leftListRightDataLayout, InlineInput, Datepicker, VPagination, noData },
    created () {
      this.formList = this.formList_obj
      this.sidebarTab = this._P.fixUrl('tab')
      this.searchSymbol = this._P.fixUrl('symbol')
    },
    data () {
      return {
        formList: {},
        sidebarTab: null,
        searchSymbol: null,
        investmentTab: 'processing',
        investmentProcessingData: [],
        investmentHistoryData: [],
        incomeRecordData: [],
        totalEarnings: null, // 当前查询总收益
        investmentProcessingDataPage: {
          count: '',
          page: 1,
          pageSize: 10
        },
        investmentHistoryDataPage: {
          count: '',
          page: 1,
          pageSize: 10
        },
        incomeRecordDataPage: {
          count: '',
          page: 1,
          pageSize: 10
        },
        // coinList: null,
        dataTimePickerValue: this.getLocalTime(),
        dataTimePickerLanguage: en,
        disabledDates: { // 限制时间选择范围  是 2018-12-31 --- 当前月
          to: new Date('Mon Dec 31 2018 19:47:00 GMT+0800 (中国标准时间)'),
          from: new Date(new Date().getTime() + 1000 * 60 * 60 * 24),
          daysOfMonth: undefined
        },
        axiosDate: this.dateProcessing(new Date()) // 获取收益明细 和 交易明细 的 年月 参数
      }
    },
    mounted () {
      this.setDateTimePickerLang(localStorage.getItem('lan')) // 设置 时间选择 插件 的  语言
      if (this.sidebarTab === 'myInvestment') {
        setTimeout(() => {
          this.investmentRecord(this.searchSymbol, this.axiosStatus)
        }, 300)
      } else if (this.sidebarTab === 'incomeDetail') {
        setTimeout(() => {
          this.earningsRecord(this.incomeAxiosSymbol, this.axiosDates)
        }, 300)
      }
    },
    computed: {
      ...mapState({
        publicInfo ({baseData}) {
          if (baseData.isReady) {
            // this.coinList = baseData._coinList
          } else {
            return false
          }
        },
        coinList ({baseData: {_coinList}}) {
          return _coinList || false
        }
      }),
      optionListCoin () {
        let arr1 = []
        let arr2 = [{value: this.Internationalization.allCurrencies, code: 'all'}]
        if (this.coinList) {
          arr1 = Object.keys(this.coinList)
          arr1.forEach(item => {
            arr2.push({value: item, code: item})
          })
        }
        return arr2
      },
      incomeOptionListCoin () {
        let arr1 = []
        let arr2 = []
        if (this.coinList) {
          arr1 = Object.keys(this.coinList)
          arr1.forEach(item => {
            arr2.push({value: item, code: item})
          })
        }
        return arr2
      },
      formList_obj () {
        return {
          currencySelection: { // 投资记录币种选择
            title: '',
            placeholder: '',
            formType: 'select',
            name: 'currencySelection',
            value: this.currencySelectionValue,
            optionList: this.optionListCoin
          },
          incomeCurrencySelection: {
            title: '',
            placeholder: '',
            formType: 'select',
            name: 'currencySelection',
            value: this.incomeCurrencySelectionValue,
            optionList: this.incomeOptionListCoin
          }
        }
      },
      currencySelectionValue () {
        if (this.searchSymbol && this.optionListCoin.length > 1) {
          return this.searchSymbol
        } else {
          return 'all'
        }
      },
      incomeCurrencySelectionValue () {
        if (this.searchSymbol && this.incomeOptionListCoin.length > 1) {
          return this.searchSymbol
        } else if (this.incomeOptionListCoin.length > 1) {
          return this.incomeOptionListCoin[0].code
        }
      },
      // 传参的symbol
      axiosSymbol () {
        let symbol = ''
        if (this.formList.currencySelection) {
          symbol = this.formList.currencySelection.value === 'all' ? '' : this.formList.currencySelection.value
        }
        return symbol
      },
      incomeAxiosSymbol () {
        return this.formList.incomeCurrencySelection ? this.formList.incomeCurrencySelection.value : ''
      },
      // 传参的 status
      axiosStatus () {
        let status = this.investmentTab === 'processing' ? 'processing' : ''
        return status
      },
      // 传参的 axiosDate
      axiosDates () {
        let axiosDate
        if (this.sidebarTab === 'myInvestment') {
          axiosDate = this.investmentTab === 'processing' ? '' : this.axiosDate
        } else if (this.sidebarTab === 'incomeDetail') {
          axiosDate = this.axiosDate
        }
        return axiosDate
      },
      statusText () {
        return this.investmentTab === 'processing' ? this.Internationalization.progressing : this.Internationalization.over
      },
      investmentProcessingDataLeng () {
        return this.investmentProcessingData.length
      },
      investmentHistoryDataLeng () {
        return this.investmentHistoryData.length
      },
      incomeRecordDataLeng () {
        return this.incomeRecordData.length
      },
      Internationalization () {
        return {
          progressing: this.$t('myAdd.bideli.progressing'), // 进行中
          over: this.$t('myAdd.bideli.over'), // 已结束
          allCurrencies: this.$t('myAdd.bideli.allCurrencies') // 已结束
        }
      }
    },
    watch: {
      'formList_obj' (newV) {
        this.formList = newV
      },
      // 监听 语言切换
      '$store.state.baseData._lan' (val, old) {
        if (old) {
          this.setDateTimePickerLang(val)
        }
      },
      investmentTab () {
        this.investmentRecord(this.axiosSymbol, this.axiosStatus, this.axiosDates)
      },
      'formList.currencySelection.value' () {
        this.investmentProcessingDataPage.page = 1
        this.investmentHistoryDataPage.page = 1
        this.incomeRecordDataPage.page = 1
        this.investmentRecord(this.axiosSymbol, this.axiosStatus, this.axiosDates)
      },
      'formList.incomeCurrencySelection.value' () {
        this.earningsRecord(this.incomeAxiosSymbol, this.axiosDates)
      }
    },
    methods: {
      somethings () {},
      changeTab (tab) {
        this.investmentTab = tab
      },
      changeSideBar (tab) {
        if (this.sidebarTab !== tab) {
          this.sidebarTab = tab
          this.sidebarTab === 'myInvestment' && this.investmentRecord(this.axiosSymbol, this.axiosStatus, this.axiosDates)
          this.sidebarTab === 'incomeDetail' && this.earningsRecord(this.incomeAxiosSymbol, this.axiosDates)
        }
      },
      // 获取当前时间
      getLocalTime () {
        return new Date()
      },
      // 日期处理
      dateProcessing (date) {
        function s (t) {
          return t < 10 ? '0' + t : t
        }
        let y = date.getFullYear()
        let m = s(date.getMonth() + 1)
        return y + '-' + m
      },
      chooseMonth (e) {
        this.axiosDate !== this.dateProcessing(e) && (this.investmentHistoryDataPage.page = 1, this.incomeRecordDataPage.page = 1) // 更换月份的时候 分页 变为 第一页
        this.axiosDate = this.dateProcessing(e)
        if (this.sidebarTab === 'myInvestment') {
          this.investmentRecord(this.axiosSymbol, this.axiosStatus, this.axiosDates)
        } else if (this.sidebarTab === 'incomeDetail') {
          this.earningsRecord(this.incomeAxiosSymbol, this.axiosDates)
        }
      },
      // 根据当前网站的语言环境 设置 时间选择插件的 语言
      setDateTimePickerLang (val) {
        switch (val) {
          case 'zh_CN':
            this.dataTimePickerLanguage = zh
            break
          case 'en_US':
            this.dataTimePickerLanguage = en
            break
          case 'ko_KR':
            this.dataTimePickerLanguage = ko
            break
          case 'el_GR':
            this.dataTimePickerLanguage = zh
            break
        }
      },
      // 投资记录
      investmentRecord (symbol, status, date) {
        let params = {
          symbol: symbol || '',
          status: status || '',
          date: date || '',
          pageSize: this.investmentTab === 'processing' ? this.investmentProcessingDataPage.pageSize : this.investmentHistoryDataPage.pageSize,
          page: this.investmentTab === 'processing' ? this.investmentProcessingDataPage.page : this.investmentHistoryDataPage.page
        }
        this.axios({
          url: this.$store.state.url.bideli.investment_record,
          method: 'POST',
          headers: {},
          params: params
        }).then(res => {
          const _self = this
          if (res.code.toString() === '0') {
            let data = res.data
            if (this.investmentTab === 'processing') {
              this.investmentProcessingDataPage.count = data.count
              this.investmentProcessingData = data.mapList
              this.investmentProcessingData.forEach(item => {
                item.time = _self._P.formatTime(item.time)
                if (_self.coinList) item.yesterDayEarnings = _self._P.lastD(_self._P.fixD(item.yesterDayEarnings, _self.coinList[item.symbol].showPrecision))
              })
            } else if (this.investmentTab === 'historicalInvestment') {
              this.investmentHistoryDataPage.count = data.count
              this.investmentHistoryData = data.mapList
              this.investmentHistoryData.forEach(item => {
                item.time = _self._P.formatTime(item.time)

                if (_self.coinList) item.yesterDayEarnings = _self._P.lastD(_self._P.fixD(item.yesterDayEarnings, _self.coinList[item.symbol].showPrecision))
              })
            }
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      },
      // 收益明细
      earningsRecord (symbol, date) {
        if (!symbol) return false
        let params = {
          symbol: symbol,
          date: date,
          pageSize: this.incomeRecordDataPage.pageSize,
          page: this.incomeRecordDataPage.page
        }
        this.axios({
          url: this.$store.state.url.bideli.earnings_record,
          headers: {},
          method: 'POST',
          params: params
        }).then(res => {
          const _self = this
          if (res.code.toString() === '0') {
            let data = res.data
            if (_self.coinList) this.totalEarnings = _self._P.lastD(_self._P.fixD(data.totalEarnings, _self.coinList[symbol].showPrecision))
            this.incomeRecordData = data.mapList
            this.incomeRecordData.forEach(item => {
              item.tiem = _self._P.formatTime(item.time)
              if (_self.coinList) item.quantity = _self._P.lastD(_self._P.fixD(item.quantity, _self.coinList[symbol].showPrecision))
            })
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      },
      // 进行中 数据 分页
      investmentProcessingDataPageChange (page) {
        this.investmentProcessingDataPage.page = page
        this.investmentRecord(this.axiosSymbol, this.axiosStatus, this.axiosDates)
      },
      // 历史数据分页
      investmentHistoryDataPageChange (page) {
        this.investmentHistoryDataPage.page = page
        this.investmentRecord(this.axiosSymbol, this.axiosStatus, this.axiosDates)
      },
      // 收益明细 分页
      incomeRecordDataPageChange (page) {
        this.incomeRecordDataPage.page = page
        this.earningsRecord(this.incomeAxiosSymbol, this.axiosDates)
      },
      // 去 购买页面
      toBideliBuying (item) {
        this.$router.push({
          path: '/bideliBuy',
          query: {
            id: item.configId,
            symbol: item.symbol,
            recordId: item.id
          }
        })
      },
      // 返回上一页
      goBack () {
        this.$router.go(-1)
      }
    }
  }
</script>

